import { ref, reactive } from 'vue'
import app from '@/app'
import store from '@/app/store'
import { get } from '@/api/erp/outbound'

// 初始化
const outboundStore = store()

// 分页
outboundStore.page = reactive({
  current: 1,
  pageSize: 0,
  total: 0,
  pageSizeOptions: [10, 20, 50, 100],
  loading: false
})

// 查询类型
outboundStore.where = reactive({ 
  key: 'code', 
  value: '',
  time: []
})

// 生成查询数据
outboundStore.getWhere = () => {
  // 查询方式
  const where = { 
    [outboundStore.where.key]: outboundStore.where.value,
    time: outboundStore.where.time
  }
  // 合并数据
  return Object.assign(where, outboundStore.getData())
}

outboundStore.get = () => {
  return new Promise((resolve, jeject) => {
    outboundStore.page.loading = true
    get(outboundStore.getWhere()).then(res => {
      const list = res.data.map((item, index) => {
        item.created_at = app.time.load(item.created_at)
        return item
      })
      outboundStore.setList(list)
      // 分页
      outboundStore.page.current = res.current_page
      outboundStore.page.pageSize = res.per_page
      outboundStore.page.total = res.total
      resolve(res)
    }).catch(res => {
      jeject(res)
    }).finally(() => {
      outboundStore.page.loading = false
    })
  })
}

// 重置请求
outboundStore.reset = (page, size) => {
  outboundStore.page.current = page
  outboundStore.page.pageSize = size
  outboundStore.getData().page = page
  outboundStore.getData().page_size = size

  // 开始加载
  outboundStore.get()
}

export default outboundStore